package controllers.participant;

import java.util.Collection;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import services.AssessService;
import services.EventService;
import controllers.AbstractController;
import domain.Assess;
import domain.Event;
import domain.Route;

@Controller
@RequestMapping("/assess/participant")
public class AssesParticipantController extends AbstractController {
	@Autowired
	private EventService eventService;
	@Autowired
	private AssessService assessService;

	public AssesParticipantController() {
		super();
	}

	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public ModelAndView edit(@RequestParam int eventId) {
		ModelAndView result;
		Assess assess = assessService.create();
		Event evento = eventService.findOne(eventId);
		Collection<Route> routes = evento.getRoutes();
		result = new ModelAndView("assess/edit");
		result.addObject("assess", assess);
		result.addObject("routes", routes);
		result.addObject("requestURI", "assess/participant/edit.do");

		return result;

	}

	@RequestMapping(value = "/edit", method = RequestMethod.POST, params = "save")
	public ModelAndView save(@Valid Assess assess, BindingResult binding) {
		ModelAndView result;

		if (binding.hasErrors()) {
			result = createEditModelAndView(assess);
		} else {
			try {
				assessService.save(assess);
				result = new ModelAndView("welcome/index");
			} catch (Throwable oops) {
				result = createEditModelAndView(assess, "assess.commit.error");
			}
		}

		return result;
	}

	protected ModelAndView createEditModelAndView(Assess assess) {
		ModelAndView result;
		result = createEditModelAndView(assess, null);
		return result;

	}

	protected ModelAndView createEditModelAndView(Assess assess, String message) {
		ModelAndView result;

		result = new ModelAndView("assess/edit");
		result.addObject("assess", assess);
		result.addObject("message", message);

		return result;

	}

}